import React, { useEffect, useState } from 'react'
import './TagManager.less'
import { GroupStore } from '../../store/GroupStore';
import tagGroupStore from '../../store/TagGroupStore';
import userGroupStore from '../../store/UserGroupStore';
import friendStore from '../../store/FriendStore'
import { VirualGroupItem } from '../../interface/IGroup';
import { observer, useLocalStore} from 'mobx-react';
import { Icon, Input, message } from 'antd';
import Modal from 'antd/es/modal';
import SvgIcon from '../../component/svgIcon/SvgIcon';
import { AvatorWithPhoto } from '../../component/avatorWithPhoto/AvatorWithPhoto';
import { ChatGrOrFrType } from '../../interface/IChat';
import Search from 'antd/lib/input/Search';
import { SelectFriend } from '../../component/selectFriend/SelectFriend';
import { FriendItem } from '../../interface/IFriend';
import { TitleEditorModal } from '../../component/titleEditorModal/TitleEditorModal';

interface ITagManagerProps{

}

interface WithStoreGroup extends ITagManagerProps {
	groupStore: GroupStore;
}



const TagManager = observer((props:ITagManagerProps) => {
  const store = useLocalStore(() => ({
    selectedIndex:0,
    showClear:false,
    keyword:'',
   
    groupEditing:{
      show:false,
      edit:false,
      type:'group',
      value:''
    },
    groupMemberEditing:{ show:false, value:'',type:'tag', action:'remove', filters:[]},
    setKeyword:(keyword:string)=>{
      store.keyword = keyword;
    },
    setShowClearSearch:(show:boolean)=>{
      store.showClear = show;
    },
    setSelected:(idx:number)=>{
      store.selectedIndex = idx;
    },
    setGroupEditing:(info:any)=>{
      store.groupEditing = info;	
    },
    setGroupMemberEditing:(info:any)=>{
      store.groupMemberEditing = info;
    }
  }));
  const tagGroups = (tagGroupStore.groupList||[]).filter(item=>{
    return item.name.indexOf(store.keyword) != -1
  })
  const current = tagGroups.length ? (tagGroups[store.selectedIndex]||{}):{
    name:'',
    members:[]
  }
  let members = current? current.members : []
  //members = members.concat(members).concat(members).concat(members).concat(members).concat(members).concat(members).concat(members).concat(members).concat(members).concat(members).concat(members).concat(members)
  const renderQuickEditModal =()=>{
    const info = store.groupEditing
    return (
      <div>
        <TitleEditorModal
           dialogTitle={info.type == 'group'?`${info.edit?'编辑':'添加'}用户分组`:`${info.edit?'编辑':'添加'}用户标签`}
           visible={store.groupEditing.show}
           onOk={(value)=>{
            store.setGroupEditing({
              ...info,
              show:false,
              type:'tag'
            })
            tagGroupStore.createTagGroup(value);
          }}
          onCancel={()=>{
            store.setGroupEditing({
             ...info,
              show:false,
              type:'tag'
            })
          }}
          onChange={(value)=>{
            store.setGroupEditing({
              ...info,
               value
             })
          }}
        ></TitleEditorModal>


        
      </div>
    )
  }
  const renderQuickEditMemberModal = ()=>{
    const info = store.groupMemberEditing
    return (
      <div>
        <TitleEditorModal
           dialogTitle={info.type == 'group'?`编辑分组成员`:`编辑标签成员`}
           visible={info.show}
           onOk={(value)=>{
            store.setGroupMemberEditing({
              ...info,
              show:false,
              type:'tag'
            })
            
          }}
          onCancel={()=>{
            store.setGroupMemberEditing({
             ...info,
              show:false,
              type:'tag'
            })
          }}
          onChange={(value)=>{
            store.setGroupEditing({
              ...info,
                value
              })
          }}
        ></TitleEditorModal>
        
      </div>
    )
  }
  let friendList = friendStore.friendList.concat();
  // 这里是个坑点，friendList时是未分组好友，还要和分组好友进行合并一个
  const groupsFriends = userGroupStore.groupList.map(item=>{
    let members:any = item.members || []
    friendList = friendList.concat(members)
  })
  friendList = friendList.map(item=>{
    return {
      ...item, 
      isSelected: members.find(m=>m.toUserId == item.toUserId)!=null
    }
  })
  return <div className="tag-manager-outter">
    {
      renderQuickEditModal()
    }
    { store.groupMemberEditing.show ? (
        <SelectFriend
          title='选择好友'
          dialogTitle={`选择${store.groupMemberEditing.action=='remove'?'移出':''}好友`}
          confirmText='确定'
          selected={members}
          isShow={ store.groupMemberEditing.show}
  
          selectConfirm={(list:FriendItem[])=>{
            //userGroupStore.addUsersGroup(list.map(item=> item.toUserId+''),store.groupMemberEditing.value);
            let oldUsers = members.concat();
            tagGroupStore.updateUsersTags(list.map(item=> item.toUserId+''),oldUsers,store.groupMemberEditing.value, true);
            store.setGroupMemberEditing({
              show:false,type:'tag'
            })
            message.info('操作成功')
          }}
          cancel={()=>{
            store.setGroupMemberEditing({
              show:false,type:'tag'
            })
          }}
          action={store.groupMemberEditing.action}
          friendList={friendList}
          members={members}
        />
      ) : null}
    <div className='tag-manager'>
    <div className='tag-manager__header'>
      <Input
        // suffix={
        //   store.showClear ? <Icon type="close-circle" theme="filled" style={{ color: '#8CA6F5' }} onClick={()=>store.setShowClearSearch(false)} /> : null
        // }
        size={"default"}
        onFocus={()=> store.setShowClearSearch(true)}
        placeholder="搜索标签名"
        maxLength={30}
        onChange={(e)=>{
          store.setKeyword(e.target.value)
        }}
        prefix={<SvgIcon size="12" name="search"></SvgIcon>}
        className="custom-input-gray"
      />

    </div>
    <div className='tag-manager__content'>
      <div className="tag-manager__bar">
        <div className='tag-manager__bar-title'>
          <h3>标签列表</h3>
          <span className='btn' onClick={()=>{
            store.setGroupEditing({
              show:true,
              edit:false,
              type:'tag',
            })
          }}>
            <SvgIcon name="group-add" size='12'/> 添加标签
          </span>
          
        </div>
        <div className="list-wrapper">
          {
            tagGroups.map((group, index) => {
              return <div className={`tag-manager__bar-item ${store.selectedIndex==index?'item-selected':''}`} key={index} onClick={()=>{
                store.setSelected(index);
              }}>
                <span className='label'>{group.name}</span>
                <span className="action">
                  <span> { group.members? group.members.length:0 }</span>
                  <span className="delete"  onClick={(e)=>{
                        e.stopPropagation();
                        if( group.members.length > 0){
                          Modal.confirm({
                            title: '标签里面存在用户，确定删除吗？',
                            okText: '确定',
                            cancelText: '取消',	
                            onOk: ()=>{
                              tagGroupStore.removeTagGroup(group.name);
                              store.setSelected(0)
                            }
                          })
                        }else{
                          tagGroupStore.removeTagGroup(group.name);
                          store.setSelected(0)
                        }
                        
                      }} >
                    <Icon type="delete"/>
                  </span>
                </span>
              </div>
            })

          }
        </div>
      </div>
      <div className='tag-manager__wrapper'>
        <div className="inner">
          <h3>{ current.name } </h3>
          <div className='list-wrapper'>
            {
              members.map((member, index) => {
                return <div className='tag-manager__item' key={index}>
                  <AvatorWithPhoto 
                      forceUpdate={false}
                      size={40}
                      type={ChatGrOrFrType.friend} 
                      onlineStyle='dot'
                      onlinestate={member.onlinestate}
                      id={member.toUserId} classN="userphoto"
                      />
                  <span className="name" title={ member.toNickname || member.nickname || member.name}>
                    { member.toNickname || member.nickname || member.name }
                  </span>
                </div>
                
              })
            }
            <div className='tag-manager__item'>
              <span className="button add" onClick={()=>{
                store.setGroupMemberEditing({
                  show:true,
                  value:current.name,
                  type:'tag'
                })
              }}>
                <SvgIcon name="tag-add-user" size='40'/>
              </span>
              <span className="name">
                添加
              </span>
            </div>
            
            <div className='tag-manager__item'>
              <span className="button add" onClick={()=>{
                store.setGroupMemberEditing({
                  show:true,
                  value:current.name,
                  type:'tag',
                  action:'remove',
                  filters:members
                })
              }}>
                <SvgIcon name="tag-remove-user" size='40'/>
              </span>
              <span className="name">
                移出
              </span>
            </div>
          </div>
        </div>
        
      </div>
    </div>
  </div>
  </div>
})

export default TagManager
